package org.xiaom.butler.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.xiaom.butler.util.HibernateUtil;
import org.xiaom.butler.util.Standard;

public class BaseService {
	Session s;
	Class clazz;

	private BaseService() {
		super();
		s = HibernateUtil.getCurrentSession();
	}

	public BaseService(Class clazz) {
		this.clazz = clazz;
		s = HibernateUtil.getCurrentSession();
	}

	public String saveOrUpdate(Object bean) {
		String rs = Standard.SERVICE_SUCCESS;
		Transaction t = s.beginTransaction();
		try {
			s.saveOrUpdate(bean);
			t.commit();
			s.flush();
		} catch (Exception e) {
			rs = Standard.SERVICE_FAIL;
			t.rollback();
			e.printStackTrace();
		}
		s.clear();
		return rs;
	}

	public String delete(Integer id) {
		String rs = Standard.SERVICE_SUCCESS;
		Transaction t = s.beginTransaction();
		try {
			Object o = get(id);
			s.delete(o);
			t.commit();
			s.flush();
		} catch (Exception e) {
			rs = Standard.SERVICE_FAIL;
			t.rollback();
			e.printStackTrace();
		}
		s.clear();
		return rs;
	}

	public Object get(Integer id) {
		return s.get(clazz, id);
	}

	public Object get(String id) {
		s.clear();
		return s.get(clazz, Integer.parseInt(id));
	}

	public List getList(String hql) {
		s.clear();
		return s.createQuery(hql).list();
	}

	private void despose() {
		s.flush();
		s.close();
	}

	public Class getClazz() {
		return clazz;
	}

	public void setClazz(Class clazz) {
		this.clazz = clazz;
	}

}
